package com.edu.hre.db.sql.admin;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import com.edu.hre.common.utils.CommonUtils;
import com.edu.hre.db.pojo.HreCustomer;
import com.edu.hre.db.pojo.HreProject;
import com.edu.hre.db.service.BaseService;
import com.edu.hre.db.utils.Compare;
import com.edu.hre.struts.form.admin.CustomerForm;
import com.edu.hre.struts.form.admin.CustomerListForm;

public class CustomerDAOService implements Serializable {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 3394301416150421253L;
	public static final String BEAN_NAME = "customerDAOService";
	private BaseService baseService  = null;
	 
	public void setBaseService(BaseService baseService) {
		this.baseService = baseService;
	} 

	public ArrayList<CustomerForm> getCustomerListInfo(int limit, int offset){
		
		List<HreCustomer> hreCustomers = baseService.getPojos("isDeleted", Compare.EQUAL, false, new String[]{"dateCreated"}, new Boolean[]{true}, limit, offset, HreCustomer.class);
		ArrayList<CustomerForm> customers = new ArrayList<CustomerForm>();
		
		if (hreCustomers == null) {
			return customers;
		}
		for (HreCustomer hreCus: hreCustomers) {

			try {

				CustomerForm customer = new CustomerForm();
				customer.setId(hreCus.getCustomerId() + "");
				customer.setName(CommonUtils.normalizeString(hreCus.getName()));
				customer.setDescription(CommonUtils.normalizeString(hreCus.getDescription()));
				customers.add(customer);
			} catch (Exception e) {
				CommonUtils.println(e.getMessage());
			}
		}

		return customers;
	}
	
	public int countCustomers() {

		int count = baseService.countByColumns(new String[]{"isDeleted"}, new int[]{Compare.EQUAL}, new Boolean[]{false}, "customerId", HreCustomer.class);
		return count < 0 ? 0 : count;
	}

	public void deleteCustomers(CustomerListForm form){

		ArrayList<CustomerForm> info = (ArrayList<CustomerForm>) form.getAllCustomers();

		for (int i = 0; i < info.size(); i++) {
			
			try {
				CustomerForm customer = info.get(i);
				if (customer.isSelected()) {
					
					HreCustomer selected = baseService.getFirstPojo("customerId", Compare.EQUAL, Integer.parseInt(customer.getId()), null, null, 0, HreCustomer.class);
					selected.setIsDeleted(true);
					boolean status = baseService.saveOrUpdate(selected);
					
					if (status) {
						deleteRelatedProject(selected.getCustomerId());
					}
				}
			} catch (Exception e) {
				CommonUtils.println(e.getMessage());
			}
		}
	}
	
	private void deleteRelatedProject (int customerId) {

		List<HreProject> deletingPros = baseService.getPojos("customerId", Compare.EQUAL, customerId, null, null, -1, 0, HreProject.class);
		
		if (deletingPros == null) {
			return;
		}
		
		for (HreProject tmp: deletingPros) {
			tmp.setIsDeleted(true);
			baseService.saveOrUpdate(tmp);
		}
	}
}
